package com.tencent.qf.common.gateway.activitymanager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.tencent.qf.common.constants.WebConstants;
import com.tencent.qf.common.exception.ErrorCode;
import com.tencent.qf.common.exception.ServiceException;
import com.tencent.qf.common.gateway.activitymanager.DTO.SignRulerSettingsInfoDTO;
import com.tencent.qf.common.gateway.activitymanager.DTO.SpecialAreaGoodsConfigDTO;
import com.tencent.qf.common.pojo.ActivityManagerHttpResult;
import com.tencent.qf.common.redis.RedisKeyConstants;
import com.tencent.qf.common.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * @author: p_haojiawu@tencent.com
 * @date: 2023-04-07 14:52
 **/

@Slf4j
@Service
public class ActivityManagerService {

    @Resource
    private ActivityManagerClient activityManagerClient;

    @Resource
    private RedisTemplate redisTemplate;

    public List<SignRulerSettingsInfoDTO> getSignRuleConfigList() {
        String result = activityManagerClient.post(new HashMap<>(), ActivityManagerApiPath.SIGN_RULER_GET);
        if (StringUtils.hasText(result)) {
            ActivityManagerHttpResult<List<SignRulerSettingsInfoDTO>> httpResult = JSON.parseObject(result,
                    new TypeReference<ActivityManagerHttpResult<List<SignRulerSettingsInfoDTO>>>() {
                    });
            if (ErrorCode.SUCCESS.getCode().toString().equals(httpResult.getCode())) {
                List<SignRulerSettingsInfoDTO> signRulerSettingsInfoDTOS = httpResult.getData();
                List<SignRulerSettingsInfoDTO> correct = new ArrayList<>();
                long current = System.currentTimeMillis();
                signRulerSettingsInfoDTOS.forEach(signRulerSettingsInfoDTO -> {
                    if (current >= signRulerSettingsInfoDTO.getRulerStartDate()
                            && current <= signRulerSettingsInfoDTO.getRulerEndDate()) {
                        correct.add(signRulerSettingsInfoDTO);
                    }
                });
                log.info("签到规则配置获取成功{}：", JSON.toJSONString(correct));
                return correct;
            } else {
                log.error("调用活动后台失败：{}", httpResult.getMessage());
                throw new ServiceException(Integer.valueOf(httpResult.getCode()), httpResult.getMessage());
            }
        }
        return Collections.emptyList();
    }

    public SpecialAreaGoodsConfigDTO getSpecialAreaGoods(Long goodsSettingsId) {
        HashMap<Object, Object> reqBody = new HashMap<>(16);
        reqBody.put("id", goodsSettingsId);
        return getSetting(reqBody, String.format(RedisKeyConstants.SPECIAL_AREA_GOODS_KEY,  goodsSettingsId), ActivityManagerApiPath.SPECIAL_AREA_GOODS_GET, SpecialAreaGoodsConfigDTO.class);
    }

    /**
     * 优先从redis获取配置， redis过期的情况下调用B端获取配置（单个）
     * @param reqBody 请求参数
     * @param redisKey
     * @param url
     * @param clazz
     * @return
     * @param <T>
     */
    private <T> T getSetting(HashMap<Object, Object> reqBody, String redisKey, String url , Class<T> clazz){
        T settings = null;
        if("gray".equals(SpringContextUtils.getApplicationContext().getEnvironment().getActiveProfiles()[0])
                || !redisTemplate.hasKey(redisKey)){
            //如果是灰度，直接调用B端接口
            String result = activityManagerClient.post(reqBody, url);
            if (StringUtils.hasText(result)) {
                ActivityManagerHttpResult<T> httpResult = JSON.parseObject(result,
                        new TypeReference<ActivityManagerHttpResult<T>>() {
                        });
                if (WebConstants.WEB_SUCCESS.equals(httpResult.getCode())) {
                    settings = httpResult.getData();
                } else {
                    log.error("获取B端规则失败：{}", httpResult.getMessage());
                    throw new ServiceException(Integer.valueOf(httpResult.getCode()), httpResult.getMessage());
                }
            }
        }else{
            String result = redisTemplate.opsForValue().get(redisKey).toString();
            settings = JSONObject.parseObject(result, clazz);
        }
        return settings;
    }
}
